/**
 * 挑选出新系统中排期下有重复素材的数据
 */
import * as path from "path";
import * as fs from "fs";
import * as os from "os";

import dayjs from "dayjs";

import { planPage, planMaterialPage, planSave, planDevicePage } from "./api/newApi";
import { calcMaterialData } from "./util";

const __dirname = path.resolve();

const DIR_PATH = path.resolve(__dirname, "./excessMateilals");
const PLAN_NAMES_PATH = path.resolve(DIR_PATH, "./planNames");

(async () => {
	try {
		if (!fs.existsSync(DIR_PATH)) fs.mkdirSync(DIR_PATH);
		fs.writeFileSync(PLAN_NAMES_PATH, "");
		main();
	} catch (err) {
		console.log("err: ", err instanceof Error ? err.message : err);
	}
})();

async function main() {
	try {
		const allPlans = await planPage().then((res) => res.data?.data?.records || []);
		for (let i = 0; i < allPlans.length; i++) {
			const item = allPlans[i];
			console.log(`检查【${item.name}】`);

			// 获取原先的关联素材
			const planMaterialList = await planMaterialPage(item.code).then((res) => {
				const list: any = res.data?.data?.records || [];
				// 素材数据在 material 里面
				return list.map((e: any) => e.material);
			});

			const needList: any[] = [];
			const repeatList: any[] = [];

			planMaterialList.forEach((material: any) => {
				const idx = needList.findIndex((e: any) => e.code === material.code);
				if (idx === -1) {
					needList.push(material);
				} else {
					repeatList.push(material);
				}
			});

			if (repeatList.length) {
				const msg = `【${item.name}】排期存在重复的素材: ${repeatList.map((e) => e.name).join(", ")}`;
				console.log(msg);
				fs.appendFileSync(PLAN_NAMES_PATH, `${msg}${os.EOL.repeat(3)}`);

				// 获取原先的关联设备
				const planDeviceList = await planDevicePage(item.code).then((res) => {
					const list: any = res.data?.data?.records || [];
					// 排期数据在 device 里面
					return list.map((e: any) => e.device);
				});

				const remarks = dayjs().format("YYYY-MM-DD HH:mm:ss") + " 迁移上传";
				const saveData = {
					...item,
					remarks,
					devices: planDeviceList,
					materials: calcMaterialData(needList, item.startDate, item.startTime)
				};
				await planSave(saveData);
				console.log(`【${item.name}】排期更新成功`);
			} else {
        console.log(`【${item.name}】没有重复的素材`);
      }
		}
	} catch (err) {
		console.log("发生了错误: ", err instanceof Error ? err.message : err);
	}
}